package com.umeng.comm.ui.fragments;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.TextView;

import com.umeng.comm.core.beans.CommUser;
import com.umeng.comm.core.utils.CommonUtils;
import com.umeng.comm.core.utils.ResFinder;
import com.umeng.comm.ui.imagepicker.fragments.BaseFragment;
import com.umeng.comm.ui.imagepicker.fragments.FollowedUserFragment;
import com.umeng.comm.ui.imagepicker.presenter.impl.NullPresenter;

/**
 * Created by summersoft on 2016/5/16.
 */
public class FocusFragment extends BaseFragment<Void, NullPresenter> implements View.OnClickListener {

    /**
     * 关注的好友Fragment
     */
    FollowedUserFragment mFolloweredUserFragment;

    /**
     * 关注的话题Fragment
     */
    FollowedTopicFragment mFollowedTopicFragment;

    //列表
    private TextView mBtnOne;
    //相册
    private TextView mBtnTwo;

    protected CommUser mUser;

//    protected UserInfoPresenter mPresenter;

    /**
     * Fragment管理器
     */
    private FragmentManager mFragmentManager = null;
    /**
     * Fragment的parent view,即Fragment的容器
     */
    protected int mFragmentContainer;
    /**
     * 当前显示的Fragment
     */
    public Fragment mCurrentFragment;

    private CommUser userFocus;

    public void setUserFocus(CommUser userFocus) {
        this.userFocus = userFocus;
    }

    @Override
    protected int getFragmentLayout() {
        return ResFinder.getLayout("focus_fragment");
    }

    @Override
    protected void initWidgets() {
        super.initWidgets();
//        mFragmentManager = getActivity().getSupportFragmentManager();
        mFragmentManager = getChildFragmentManager();

//        mUser = CommConfig.getConfig().loginedUser;
        mUser = userFocus;
        int btnOneResId = ResFinder.getId("comment_switch_button_one");
        mBtnOne = (TextView) findViewById(btnOneResId);
        mBtnOne.setOnClickListener(this);

        int btnTwoResId = ResFinder.getId("comment_switch_button_two");
        mBtnTwo = (TextView) findViewById(btnTwoResId);
        mBtnTwo.setOnClickListener(this);
        initFragment();
        initTab();

    }

    private void changeSelectedTab(int i) {
        mBtnOne.setSelected(i == 0);
        mBtnTwo.setSelected(i == 1);

    }

    private void initTab() {
        changeSelectedTab(0);
    }

    public void initFragment() {

        if (mFolloweredUserFragment == null){
            mFolloweredUserFragment = FollowedUserFragment.newInstance(mUser.id);
        }

        addFragment(ResFinder.getId("umeng_focus_fragment_container"),
                mFolloweredUserFragment);
    }

    /**
     * 粉丝数的回调函数。在加载缓存或者下拉刷新时，可能需要更新显示的用户数字。
     */
//    protected Listeners.OnResultListener mFansListener = new Listeners.OnResultListener() {
//
//        @Override
//        public void onResult(final int status) {
//            if (mPresenter.isUpdateFansCountTextView()) {
//                CommonUtils.runOnUIThread(getActivity(), new Runnable() {
//
//                    @Override
//                    public void run() {
//                        mFansCountTextView.setText(String.valueOf(status));
//                    }
//                });
//            }
//        }
//    };


    /**
     * 判断一个Fragment是否已经添加
     *
     * @param fragment 要判断是否已经添加的Fragment
     * @return
     */
    public boolean isFragmentAdded(Fragment fragment) {
        return fragment != null
                && mFragmentManager.findFragmentByTag(fragment.getClass().getName()) != null;
    }

    /**
     * @param container 用于放置fragment的布局id
     * @param fragment  要添加的Fragment
     */
    public void addFragment(int container, Fragment fragment) {

        FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
        if (!isFragmentAdded(fragment)) {
            fragmentTransaction
                    .add(container, fragment,
                            fragment.getClass().getName()).commitAllowingStateLoss();
            mCurrentFragment = fragment;
        } else {
//            fragmentTransaction.remove(fragment);

//            fragmentTransaction
//                    .add(container, fragment,
//                            fragment.getClass().getName()).commitAllowingStateLoss();
            fragmentTransaction.show(fragment).commitAllowingStateLoss();
        }

        mFragmentContainer = container;
    }

    /**
     * 显示Fragment，并且把上一个隐藏
     *
     * @param fragmentShow
     */
    public void showFragment(Fragment fragmentShow) {
        showFragmentInContainer(mFragmentContainer, fragmentShow);
    }

    /**
     * 将fragmentShow显示在一个新的container上,而不覆盖mFragmentContainer。
     * 这种情况适用于Fragment中又嵌套Fragment
     *
     * @param container
     * @param fragmentShow
     */
    public void showFragmentInContainer(int container, Fragment fragmentShow) {
        checkContainer();

        if (mCurrentFragment != fragmentShow) {
            FragmentTransaction transaction = mFragmentManager.beginTransaction();
            if (mCurrentFragment != null) {
                // 首先隐藏原来显示的Fragment
                transaction.hide(mCurrentFragment);
            }
            // 然后再显示传递进来的Fragment
            if (mFragmentManager.findFragmentByTag(fragmentShow.getClass().getName()) == null) {
                transaction
                        .add(container, fragmentShow, fragmentShow.getClass().getName());
            } else {
                transaction.show(fragmentShow);
            }
            transaction.commitAllowingStateLoss();
            mCurrentFragment = fragmentShow;
        }
    }

    /**
     * 检查放置fragment的布局id
     */
    private void checkContainer() {
        if (mFragmentContainer <= 0) {
            throw new RuntimeException(
                    "在调用replaceFragment函数之前请调用setFragmentContainerId函数来设置fragment container id");
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        if (id == ResFinder.getId("comment_switch_button_one")) {// 已发消息

            if (mCurrentFragment instanceof FollowedUserFragment) { // 已经处于当前页面，判断是否需要滚动到起始位置
                mFolloweredUserFragment.executeScrollTop();
            } else {
                if (mFollowedTopicFragment != null){//切换到关注的人时，要清空关注的话题,才不会两个项会窜在一起
                    transaction.remove(mFollowedTopicFragment);
                }
                if (mFragmentManager.findFragmentByTag(mFolloweredUserFragment.getClass().getName()) == null){
                    showFragment(mFolloweredUserFragment);
                }else {
                    transaction.remove(mFolloweredUserFragment);
                    mFolloweredUserFragment = FollowedUserFragment.newInstance(mUser.id);
                    transaction
                            .add(mFragmentContainer, mFolloweredUserFragment, mFolloweredUserFragment.getClass().getName());
                    transaction.commitAllowingStateLoss();
                }
            }
            changeSelectedTab(0);
        } else if (id == ResFinder.getId("comment_switch_button_two")) {// 关注用户

            if (mFolloweredUserFragment != null){//切换到关注的话题时，要清空关注的人,才不会两个项会窜在一起
                transaction.remove(mFolloweredUserFragment);
            }
            if (mFollowedTopicFragment == null) {
                mFollowedTopicFragment = FollowedTopicFragment.newFollowedTopicFragment(mUser.id);
//                if (mFragmentManager.findFragmentByTag(mFollowedTopicFragment.getClass().getName()) != null){//底部菜单切换的时候，要清除
                    transaction.remove(mFollowedTopicFragment);
                    mFollowedTopicFragment = FollowedTopicFragment.newFollowedTopicFragment(mUser.id);
                    transaction
                            .add(mFragmentContainer, mFollowedTopicFragment, mFollowedTopicFragment.getClass().getName());

                    transaction.commitAllowingStateLoss();

                    mCurrentFragment = mFollowedTopicFragment;
//                }else {
//                    showFragment(mFollowedTopicFragment);
//                }
            }else {

                if (mFragmentManager.findFragmentByTag(mFollowedTopicFragment.getClass().getName()) == null) {
                    transaction
                            .add(mFragmentContainer, mFollowedTopicFragment, mFollowedTopicFragment.getClass().getName());
                } else {
                    mFollowedTopicFragment = FollowedTopicFragment.newFollowedTopicFragment(mUser.id);
                    transaction
                            .add(mFragmentContainer, mFollowedTopicFragment, mFollowedTopicFragment.getClass().getName());
                }
                transaction.commitAllowingStateLoss();

                mCurrentFragment = mFollowedTopicFragment;
            }
            changeSelectedTab(1);
        }
    }

    /**
     * 切换到粉丝时，没有及时清空下面层级的fragment
     */
    public void removeAllFragment(){
        FragmentTransaction transaction = mFragmentManager.beginTransaction();
        if (mFolloweredUserFragment != null){
            transaction.remove(mFolloweredUserFragment);
        }
        if (mFollowedTopicFragment != null){
            transaction.remove(mFollowedTopicFragment);
        }
        transaction.commitAllowingStateLoss();
    }

    protected void ReceiverComplete(CommUser user, boolean follow) {
        if (mFolloweredUserFragment != null) {
            if (CommonUtils.isLogin(getActivity())) {
                mFolloweredUserFragment.updateFollowedState(user.id, follow);
            }
        }
    }

}
